<?php

namespace Admin\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;


class UserTable extends AbstractTableGateway {

    protected $table = 'nguoidung';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new User());

        $this->initialize();
    }

    public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'))
				->join(
					'quyen',
					'quyen.id = nguoidung.quyen',
					array('tenquyen'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }

    public function getUser($id) {
        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current(); 
        return $row;
    }

    public function saveUser(User $user) {
		
			
		
        

        $id = (int) $user->id;
        if ($id == 0) {
			$data = array(
				'username' => $user->username,
				'password' => md5($user->password),
				'email' => $user->email,
				'hoten' => $user->hoten,
				'quyen' => $user->quyen,
			);
            	
                $this->insert($data);
            
        } else {
			
			$data = array(
				'username' => $user->username,
				'email' => $user->email,
				'password' => $user->password,
				'hoten' => $user->hoten,
				'quyen' => $user->quyen,
			);
            if ($this->getUser($id)) {
				
					$this->update($data, array('id' => $id));
				
            } else {
                throw new \Exception('Không tồn tại');
            }
        }
    }

    public function deleteUser($id) {
        $this->delete(array('id' => $id));
    }
	public function xoaUser($id) {
		
        $this->delete('id IN (' . $id . ')');
    }
	
	//kiem tra ton tai
	public function check_exists($username,$id)
	{
		//$rowset = $this->select(array('title' => $title));
        //$row = $rowset->current();
		$resultSet = $this->select(array('username = "'.$username.'"', 'id != "'.$id.'"'));
    	$row = $resultSet->current();
        return $row;
		
	}
	public function check_email($email,$id)
	{
		//$rowset = $this->select(array('title' => $title));
        //$row = $rowset->current();
		$resultSet = $this->select(array('email = "'.$email.'"', 'id != "'.$id.'"'));
    	$row = $resultSet->current();
        return $row;
		
	}


}
